package com.longcai.piaojia.fragment;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.longcai.piaojia.BaseApplication;
import com.longcai.piaojia.R;
import com.longcai.piaojia.activity.DepositActivity;
import com.longcai.piaojia.activity.FeedBackActivity;
import com.longcai.piaojia.activity.LoginActivity;
import com.longcai.piaojia.activity.MyAboutUsActivity;
import com.longcai.piaojia.activity.MyAccountManagerActivity;
import com.longcai.piaojia.activity.MyAppointmentActivity;
import com.longcai.piaojia.activity.MyBagActivity;
import com.longcai.piaojia.activity.MyCampaignActivity;
import com.longcai.piaojia.activity.MyCollectionListActivity;
import com.longcai.piaojia.activity.MyCouponActivity;
import com.longcai.piaojia.activity.MyIntegrationActivity;
import com.longcai.piaojia.activity.MyOrderListActivity;
import com.longcai.piaojia.activity.ProblemsActivity;
import com.longcai.piaojia.conn.Conn;
import com.longcai.piaojia.conn.MinePersonalInfoGet;
import com.longcai.piaojia.dialog.WarnningDialog;
import com.longcai.piaojia.util.UtilPermission;
import com.longcai.piaojia.util.VirtualBackground;
import com.longcai.piaojia.widget.LoadUsefulView;
import com.zcx.helper.app.AppCallBack;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.glide.GlideLoader;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;
import com.zcx.helper.util.UtilApp;
import com.zcx.helper.util.UtilData;

import java.math.BigDecimal;

/**
 * Created by Administrator on 2016/8/2.
 */
public class MineFragment extends BaseFragment implements View.OnClickListener {


    @BoundView(R.id.mine_userinfo_rl) private RelativeLayout mine_userinfo_rl;
    @BoundView(R.id.mine_username_tv) private TextView mine_username_tv;
    @BoundView(R.id.mine_phonenum_tv) private TextView mine_phonenum_tv;
    @BoundView(R.id.mine_coupon_count_tv) private TextView mine_coupon_count_tv;
    @BoundView(R.id.mine_integral_tv) private TextView mine_integral_tv;
    @BoundView(R.id.mine_cleancache_tv) private TextView mine_cleancache_tv;

    @BoundView(R.id.fragment_mine_not_login_coupon_tv) private TextView fragment_mine_not_login_coupon_tv;
    @BoundView(R.id.fragment_mine_login_coupon_ll) private LinearLayout fragment_mine_login_coupon_ll;

    @BoundView(R.id.fragment_mine_not_login_integral_tv) private TextView fragment_mine_not_login_integral_tv;
    @BoundView(R.id.fragment_mine_login_integral_ll) private LinearLayout fragment_mine_login_integral_ll;

    @BoundView(R.id.fragment_mine_not_login_purse_tv) private TextView fragment_mine_not_login_purse_tv;
    @BoundView(R.id.fragment_mine_login_purse_ll) private LinearLayout fragment_mine_login_purse_ll;
    @BoundView(R.id.mine_purse_rl) private RelativeLayout mine_purse_rl;
    @BoundView(R.id.mine_purse_tv) private TextView mine_purse_tv;

    @BoundView(R.id.mine_menu_ll) private LinearLayout mine_menu_ll;

    @BoundView(R.id.mine_account_manager_ll) private LinearLayout mine_account_manager_ll;
    @BoundView(R.id.mine_head_icon_iv) private ImageView mine_head_icon_iv;
    @BoundView(R.id.mine_title_bg_iv) private ImageView mine_title_bg_iv;
    @BoundView(R.id.mine_title_noLogin_bg_iv) private ImageView mine_title_noLogin_bg_iv;
    @BoundView(R.id.mine_coupon_rl) private RelativeLayout mine_coupon_rl;
    @BoundView(R.id.mine_integral_rl) private RelativeLayout mine_integral_rl;

    @BoundView(R.id.mine_order_ll) private LinearLayout mine_order_ll;
    @BoundView(R.id.mine_bag_ll) private LinearLayout mine_bag_ll;
    @BoundView(R.id.mine_appointment_ll) private LinearLayout mine_appointment_ll;
    @BoundView(R.id.mine_collection_ll) private LinearLayout mine_collection_ll;
    @BoundView(R.id.mine_cleancache_ll) private LinearLayout mine_cleancache_ll;
    @BoundView(R.id.mine_feedback_ll) private LinearLayout mine_feedback_ll;
    @BoundView(R.id.mine_problems_ll) private LinearLayout mine_problems_ll;
    @BoundView(R.id.mine_invite_ll) private LinearLayout mine_invite_ll;
    @BoundView(R.id.mine_call_service_ll) private LinearLayout mine_call_service_ll;
    @BoundView(R.id.mine_about_us_ll) private LinearLayout mine_about_us_ll;
    @BoundView(R.id.mine_Logout_ll) private LinearLayout mine_Logout_ll;
    @BoundView(R.id.fragment_mine_above_logout_line_ll) private LinearLayout fragment_mine_above_logout_line_ll;//这个是 退出登录上面的那条线
    @BoundView(R.id.mine_is_huimin_icon_iv) private ImageView mine_is_huimin_icon_iv;//这个是 是否是惠民会员的图标



    private MinePersonalInfoGet.PersonalInfoEntity personalInfo;

    private getUserAdvert getUserAd;

    private MinePersonalInfoGet minePersonalInfoGet = new MinePersonalInfoGet(new AsyCallBack<MinePersonalInfoGet.PersonalInfoEntity>(){
        @Override
        public void onSuccess(String toast, int type, MinePersonalInfoGet.PersonalInfoEntity personalInfoEntity) throws Exception {

            personalInfo = personalInfoEntity;

            getUserAd.updateCoupon(personalInfoEntity.coupon);
            getUserAd.updateMyPurse(new BigDecimal(personalInfoEntity.wallet).add(new BigDecimal(personalInfoEntity.privilege)).toString());
            getUserAd.updateIntegral(personalInfoEntity.integral);
            getUserAd.updateName(personalInfoEntity.nickname);
            getUserAd.updatePhone(BaseApplication.BasePreferences.readUserAccount());

            try{

                getUserAd.updateAdvert(personalInfo.avatar);

            }catch (Exception e){
                e.printStackTrace();
            }


        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            Toast.makeText(getActivity(), toast, Toast.LENGTH_SHORT).show();
        }
    });
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = BoundViewHelper.boundView(this, inflater.inflate(R.layout.fragment_mine, null));

        String[] permission = { Manifest.permission.CALL_PHONE};
        UtilPermission.Permission(getActivity(), permission);

        DisplayMetrics metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;  // 屏幕宽度（像素）

        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mine_userinfo_rl.getLayoutParams();
        layoutParams.height = width;
        mine_userinfo_rl.setLayoutParams(layoutParams);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.topMargin = -((width - ScaleScreenHelperFactory.getInstance().getWidthHeight(255))+ScaleScreenHelperFactory.getInstance().getWidthHeight(118));

        mine_menu_ll.setLayoutParams(params);

        if(BaseApplication.BasePreferences.readIsLogin()){

            if(BaseApplication.BasePreferences.readIsFavourable().equals("2")){

                mine_is_huimin_icon_iv.setVisibility(View.VISIBLE);

            }else{

                mine_is_huimin_icon_iv.setVisibility(View.GONE);

            }

        }

        mine_account_manager_ll.setOnClickListener(this);
        mine_coupon_rl.setOnClickListener(this);
        mine_integral_rl.setOnClickListener(this);
        mine_order_ll.setOnClickListener(this);
        mine_bag_ll.setOnClickListener(this);
        mine_collection_ll.setOnClickListener(this);
        mine_cleancache_ll.setOnClickListener(this);
        mine_feedback_ll.setOnClickListener(this);
        mine_problems_ll.setOnClickListener(this);
        mine_invite_ll.setOnClickListener(this);
        mine_call_service_ll.setOnClickListener(this);
        mine_about_us_ll.setOnClickListener(this);
        mine_Logout_ll.setOnClickListener(this);
        mine_purse_rl.setOnClickListener(this);
        mine_appointment_ll.setOnClickListener(this);

        showCache();

        setAppCallBack(new getUserAdvert());

        getUserAd = new getUserAdvert();

        getUserAd.refreshInfo();


        return view;

    }

    private void showCache() {
        try {
            mine_cleancache_tv.setText(UtilData.getTotalCacheSize(getActivity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.mine_account_manager_ll:

                if (BaseApplication.BasePreferences.readIsLogin()) {

                    Bundle bundle = new Bundle();

                    bundle.putString("avatar", personalInfo.avatar);
                    bundle.putString("nickname", personalInfo.nickname);
                    bundle.putString("truename", personalInfo.truename);

                    startActivity(new Intent(getActivity(), MyAccountManagerActivity.class).putExtras(bundle));

                } else {

                    startActivity(new Intent(getActivity(), LoginActivity.class));

                }

                break;

            case R.id.mine_coupon_rl:

                if (BaseApplication.BasePreferences.readIsLogin()) {

                    startActivity(new Intent(getActivity(), MyCouponActivity.class));

                } else {

                    startActivity(new Intent(getActivity(), LoginActivity.class));

                }

                break;

            case R.id.mine_purse_rl:

                if (BaseApplication.BasePreferences.readIsLogin()) {

//                    startActivity(new Intent(getActivity(), DepositActivity.class).putExtra("privilege", personalInfo.privilege));
                    startActivity(new Intent(getActivity(), DepositActivity.class));

                } else {

                    startActivity(new Intent(getActivity(), LoginActivity.class));

                }

                break;

            case R.id.mine_integral_rl:

                if (BaseApplication.BasePreferences.readIsLogin()) {

                    startActivity(new Intent(getActivity(), MyIntegrationActivity.class));

                } else {

                    startActivity(new Intent(getActivity(), LoginActivity.class));

                }

                break;

            case R.id.mine_order_ll:

                if (BaseApplication.BasePreferences.readIsLogin()) {

                    startActivity(new Intent(getActivity(), MyOrderListActivity.class));

                } else {

                    startActivity(new Intent(getActivity(), LoginActivity.class));

                }


                break;

            case R.id.mine_bag_ll:

                if (BaseApplication.BasePreferences.readIsLogin()) {

                    startActivity(new Intent(getActivity(), MyBagActivity.class));

                } else {

                    startActivity(new Intent(getActivity(), LoginActivity.class));

                }

                break;

            case R.id.mine_appointment_ll:

                if (BaseApplication.BasePreferences.readIsLogin()) {

                    startActivity(new Intent(getActivity(), MyAppointmentActivity.class));

                } else {

                    startActivity(new Intent(getActivity(), LoginActivity.class));

                }

                break;

            case R.id.mine_collection_ll:

                if (BaseApplication.BasePreferences.readIsLogin()) {

                    startActivity(new Intent(getActivity(), MyCollectionListActivity.class));

                } else {

                    startActivity(new Intent(getActivity(), LoginActivity.class));

                }

                break;

            case R.id.mine_cleancache_ll:

                new WarnningDialog(getActivity(), getResources().getString(R.string.mine_cleancache_text)) {
                    @Override
                    protected void onConfirm() {

                        UtilData.clearAllCache(getActivity());
                        showCache();

                    }
                }.show();

                break;

            case R.id.mine_feedback_ll:

                if (BaseApplication.BasePreferences.readIsLogin()) {

                    startActivity(new Intent(getActivity(), FeedBackActivity.class));

                } else {

                    startActivity(new Intent(getActivity(), LoginActivity.class));

                }

                break;

            case R.id.mine_problems_ll:

                startActivity(new Intent(getActivity(), ProblemsActivity.class));

                break;

            case R.id.mine_invite_ll:

                if (BaseApplication.BasePreferences.readIsLogin()) {

                    startActivity(new Intent(getActivity(), MyCampaignActivity.class));

                } else {

                    startActivity(new Intent(getActivity(), LoginActivity.class));

                }

                break;

            case R.id.mine_call_service_ll:

                new WarnningDialog(getActivity(), BaseApplication.BasePreferences.readCustomServiceTel(), getString(R.string.cancel_text), getString(R.string.confirm_text)) {
                    @Override
                    protected void onConfirm() {

                        UtilApp.call(getActivity(), BaseApplication.BasePreferences.readCustomServiceTel());

                    }
                }.show();


                break;

            case R.id.mine_about_us_ll:

                startVerifyActivity(MyAboutUsActivity.class);
                break;

            case R.id.mine_Logout_ll:

                new WarnningDialog(getActivity(), getResources().getString(R.string.mine_logout_text)) {
                    @Override
                    protected void onConfirm() {

                        BaseApplication.BasePreferences.saveIsLogin(false);
                        BaseApplication.BasePreferences.saveUserId("");
                        BaseApplication.BasePreferences.saveUserAccount("");

                        getUserAd.refreshInfo();

                    }
                }.show();
                break;

        }

    }




    public class getUserAdvert implements AppCallBack {

        public void updateAdvert(String s){

            GlideLoader.getInstance().get(getActivity(), s, mine_head_icon_iv, R.mipmap.mine_headimg, GlideLoader.TYPE_IMAGE_CIRCLE);

            Glide.with(getActivity()).load(s).asBitmap().into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {

//                    DisplayMetrics metric = new DisplayMetrics();
//                    getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
//                    int width = metric.widthPixels;  // 屏幕宽度（像素）
//
//                    Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, width, ScaleScreenHelperFactory.getInstance().getWidthHeight(273));

                    Bitmap mBitmap = VirtualBackground.createScaledBitmap(bitmap, 0, 0, false);
                    mine_title_bg_iv.setImageBitmap(mBitmap);
                }
            });

            personalInfo.avatar = s;

        }

        public void updateName(String s){

            mine_username_tv.setText(s);
            personalInfo.nickname = s;

        }

        public void updatePhone(String s){

            mine_phonenum_tv.setText(s.substring(0,3) + "****" + s.substring(7));

        }

        public void updateCoupon(String s){

            mine_coupon_count_tv.setText(s);

        }

        public void updateMyPurse(String s){

            mine_purse_tv.setText(s);

        }

        public void updateIntegral(String s){

            mine_integral_tv.setText(s);

        }

        public void updateTrueName(String s){

            personalInfo.truename = s;

        }

        public void refreshInfo(){

            if (BaseApplication.BasePreferences.readIsLogin()) {

                mine_title_noLogin_bg_iv.setVisibility(View.GONE);
                mine_title_bg_iv.setImageResource(R.mipmap.mine_title_bg);
                mine_title_bg_iv.setVisibility(View.VISIBLE);

                fragment_mine_not_login_coupon_tv.setVisibility(View.GONE);
                fragment_mine_not_login_integral_tv.setVisibility(View.GONE);
                fragment_mine_not_login_purse_tv.setVisibility(View.GONE);
                fragment_mine_login_coupon_ll.setVisibility(View.VISIBLE);
                fragment_mine_login_integral_ll.setVisibility(View.VISIBLE);
                fragment_mine_login_purse_ll.setVisibility(View.VISIBLE);
                mine_phonenum_tv.setVisibility(View.VISIBLE);
                mine_Logout_ll.setVisibility(View.VISIBLE);
                fragment_mine_above_logout_line_ll.setVisibility(View.VISIBLE);

                if(BaseApplication.BasePreferences.readIsFavourable().equals("2")){

                    mine_is_huimin_icon_iv.setVisibility(View.VISIBLE);

                }else{

                    mine_is_huimin_icon_iv.setVisibility(View.GONE);

                }

                minePersonalInfoGet.user_id = BaseApplication.BasePreferences.readUserId();
                minePersonalInfoGet.execute(getActivity(), false);

            } else {

                LoadUsefulView.success(getContext(), MinePersonalInfoGet.class);

                mine_title_noLogin_bg_iv.setVisibility(View.VISIBLE);
                mine_title_bg_iv.setVisibility(View.GONE);

                fragment_mine_not_login_coupon_tv.setVisibility(View.VISIBLE);
                fragment_mine_not_login_integral_tv.setVisibility(View.VISIBLE);
                fragment_mine_not_login_purse_tv.setVisibility(View.VISIBLE);
                fragment_mine_login_coupon_ll.setVisibility(View.GONE);
                fragment_mine_login_integral_ll.setVisibility(View.GONE);
                fragment_mine_login_purse_ll.setVisibility(View.GONE);
                mine_Logout_ll.setVisibility(View.GONE);
                fragment_mine_above_logout_line_ll.setVisibility(View.GONE);
                mine_is_huimin_icon_iv.setVisibility(View.GONE);

                mine_username_tv.setText(R.string.fragment_mine_immediately_login_text);
                mine_phonenum_tv.setVisibility(View.GONE);
                mine_head_icon_iv.setImageResource(R.mipmap.mine_headimg);

//                mine_title_bg_iv.setImageResource(R.mipmap.mine_title_bg);

                Log.e("backdrop", Conn.IMAGE_BANNER_URL + BaseApplication.BasePreferences.readBackdrop());
//
                GlideLoader.getInstance().get(getContext(), Conn.IMAGE_BANNER_URL + BaseApplication.BasePreferences.readBackdrop(), mine_title_noLogin_bg_iv, R.mipmap.mine_title_bg);

            }

        }



    }

}
